package com.xiaoxin.dubbo.api;

import com.xiaoxin.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author xiaoxiaode
 * @date 2021-09-08-17:04
 **/
@SuppressWarnings("all")
@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /*
     * 添加联系人
     * */
    public void save(Long myId, Long friendId) {
        Query query = Query.query(Criteria.where("userId").is(myId).and("friendId").is(friendId));
        if (!mongoTemplate.exists(query, Friend.class)) {
            Friend friend = new Friend();
            friend.setCreated(System.currentTimeMillis());
            friend.setUserId(myId);
            friend.setFriendId(friendId);
            mongoTemplate.save(friend);
        }

        Query query2 = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(myId));
        if (!mongoTemplate.exists(query2, Friend.class)) {
            Friend friend2 = new Friend();
            friend2.setCreated(System.currentTimeMillis());
            friend2.setUserId(friendId);
            friend2.setFriendId(myId);
            mongoTemplate.save(friend2);
        }
    }

    @Override
    public List<Friend> findFriends(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId")
                .is(userId)).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        return friends;
    }

    @Override
    public void remove(Long userId, Long unlikeUserId) {
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(unlikeUserId));
        mongoTemplate.remove(query1, Friend.class);
        Query query2 = Query.query(Criteria.where("userId").is(unlikeUserId).and("friendId").is(userId));
        mongoTemplate.remove(query2, Friend.class);

    }
}
